#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <Includes.h>
#include <EC600S_AT/AT.h>
#include <DRV_EC600S.h>
#include <OPP_Debug.h>

T_MUTEX atcmdMux;
static t_queue queue_atcmd;
static U8 queue_atcmd_buf[sizeof(ST_CMD)*ATCMD_QUEUE_MAX];

/**
@brief 二进制数据调试函数
@param
	-data    数据
    -len     长度
@return
**/
int Ec600sDataDump(U8 *data, U16 len)
{
    int i=0;
    int tlen=0;
    char buffer[EC600S_MAX_MTU]={0};

    tlen+=snprintf(buffer+tlen,EC600S_MAX_MTU,"\r\nEc600sDataDump len=%d content:\r\n",len);
    for(i=0;i<len;i++)
    {
        tlen+=snprintf(buffer+tlen,EC600S_MAX_MTU,"%02x ",data[i]);
        if((i+1)%16==0)
        {
            tlen+=snprintf(buffer+tlen,EC600S_MAX_MTU,"%s","\r\n");

        }
        if(tlen>EC600S_MAX_MTU)
        {
            DEBUG_LOG(DEBUG_MODULE_EC600S, DLL_INFO,"%s\r\n",buffer);
            tlen=0;
        }
    }
    DEBUG_LOG(DEBUG_MODULE_EC600S, DLL_INFO,"%s\r\n",buffer);
    return 0;
}

/*执行单条AT指令*/
int Ec600sAtCmdOne(ST_CMD *cmd, ST_AT_EXE_OUT_DATA *odata)
{
    return AtExe(EN_DEV_TYPE_EC600S, cmd->atCmd, cmd->waitTime, cmd->atRspProc, odata);
}

/*执行序列AT指令*/
int Ec600sAtCmd(ST_CMD cmd[],int num)
{
    return AtCmd(EN_DEV_TYPE_EC600S,cmd,num);
}

int Ec600sAtCmdQueueIn(ST_CMD const *entry, int cmdlen, ...)
{
    int ret;
	va_list vl;
    ST_CMD cmd;

    memcpy(&cmd,entry,sizeof(ST_CMD));

    cmd.atCmd=(char *)malloc(cmdlen);
    if(cmd.atCmd==NULL)
    {
        return 2;
    }

    va_start(vl,cmdlen);
    vsprintf(cmd.atCmd,entry->atCmd,vl);
    va_end(vl);

    MUTEX_LOCK(atcmdMux, MUTEX_WAIT_ALWAYS);
    ret=pushQueue(&queue_atcmd, (unsigned char*)&cmd, 0);
    if(ret!=0)
    {
        DEBUG_LOG(DEBUG_MODULE_EC600S, DLL_ERROR, "push queue_atcmd err=%d\r\n",ret);
        MUTEX_UNLOCK(atcmdMux);
        return ret;
    }
    MUTEX_UNLOCK(atcmdMux);

    return 0;
}

int Ec600sAtCmdQueueOut()
{
    ST_CMD cmd;
    int ret;

    MUTEX_LOCK(atcmdMux, MUTEX_WAIT_ALWAYS);
    ret=pullQueue(&queue_atcmd, (unsigned char *)&cmd, sizeof(ST_CMD));
    if(ret!=0)
    {
        MUTEX_UNLOCK(atcmdMux);
        return ret+10;
    }
    MUTEX_UNLOCK(atcmdMux);

    ret=AtExe(EN_DEV_TYPE_EC600S, cmd.atCmd, cmd.waitTime, cmd.atRspProc, NULL);
    if(0!=ret)
    {
        DEBUG_LOG(DEBUG_MODULE_EC600S, DLL_ERROR, "cmd=%s ret=%d", cmd.atCmd, ret);
        free(cmd.atCmd);
        return ret+20;
    }
    if(cmd.action)
        cmd.action();
    free(cmd.atCmd);
    return 0;
}

int Ec600sAtCmdInit()
{
    MUTEX_CREATE(atcmdMux);
	initQueue(&queue_atcmd,queue_atcmd_buf,sizeof(ST_CMD)*ATCMD_QUEUE_MAX,ATCMD_QUEUE_MAX,sizeof(ST_CMD));
    return 0;
}

